<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class HhmGoodsOption extends Model
{
    use SoftDeletes;

    protected $table = 'ims_hhm_goods_option';
    
    protected $fillable = [
        'uniacid', 'goods_id', 'title', 'thumb',
        'product_price', 'market_price', 'cost_price',
        'stock', 'withhold_stock',
        'weight', 'volume',
        'goods_sn', 'product_sn', 'sku_id',
        'specs', 'spec_titles',
        'virtual', 'red_price', 'display_order', 'is_enabled'
    ];

    protected $casts = [
        'specs' => 'json',
        'product_price' => 'decimal:2',
        'market_price' => 'decimal:2',
        'cost_price' => 'decimal:2',
        'weight' => 'decimal:2',
        'volume' => 'decimal:3',
        'is_enabled' => 'boolean',
    ];

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    const DELETED_AT = 'deleted_at';

    // 禁用时间戳自动转换为Carbon对象，因为表中使用整型存储
    public $timestamps = true;
    protected $dateFormat = 'U'; // 使用Unix时间戳

    /**
     * 关联商品
     */
    public function goods()
    {
        return $this->belongsTo(HhmGoods::class, 'goods_id', 'id');
    }

    /**
     * 获取可用库存
     */
    public function getAvailableStockAttribute()
    {
        return max(0, ($this->stock ?? 0) - ($this->withhold_stock ?? 0));
    }

    /**
     * 获取缩略图完整URL
     */
    public function getThumbUrlAttribute()
    {
        if (empty($this->thumb)) {
            // 如果SKU没有图片，使用商品主图
            return $this->goods ? $this->goods->thumb_url : '';
        }
        return \App\Services\ImageUrlService::processImageUrl($this->thumb);
    }
}

